//
//  KKAddressBookManager.m
//  FreightAssistant
//
//  Created by leo on 15/11/9.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "KKAddressBookManager.h"

@interface KKAddressBookManager() <ABPeoplePickerNavigationControllerDelegate, UINavigationControllerDelegate> {
    
    ABPeoplePickerNavigationController *_kk_peoplePicker;
    
    ABNewPersonViewController *_personViewController;
}

@end

@implementation KKAddressBookManager

- (instancetype)init {
    self = [super init];
    if (self) {
        
        _kk_peoplePicker = [ABPeoplePickerNavigationController new];
        _kk_peoplePicker.peoplePickerDelegate = self;
        _kk_peoplePicker.displayedProperties = @[[NSNumber numberWithInt:kABPersonPhoneProperty]];
    }
    return self;
}

+ (instancetype)defaultManager {
    
    static KKAddressBookManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKAddressBookManager new];
    });
    return manager;
}

#pragma mark - Public methods

- (void)showInController:(__weak UIViewController*)controller completion:(KKAddressBookManagerBlock)completion {
    
    _callBack = [completion copy];
    _targetController = controller;
    
    [_targetController presentViewController: _kk_peoplePicker animated: true completion: nil];
}


#pragma mark -

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    
    NSDictionary *userInfo = nil;
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phone) > 0) {
        
        NSString *personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, 0);
        
        userInfo = @{@"phone":personPhone};
    }
    
    if (_callBack) {
        _callBack(userInfo);
    }
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    NSLog(@"8.0之后调用");
    // 8.0之后调用
}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    
    return true;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    return true;
}

@end
